package com.zl.test4android;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.NinePatch;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.hardware.Camera.Size;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

/**
 * @author Administrator
 *
 */
/**
 * @author Administrator
 *
 */
public class MySeekbar extends SeekBar implements OnSeekBarChangeListener,
		OnPreDrawListener {
	/**
	 * һ�����ٶ� Ĭ��Ϊ2
	 */
	private int select = 2;
	private int seekBarWidth;
	
	/**
	 * ÿһ�εĳ���
	 */
	private int dSize;
	private int max=1000;
	/**
	 * ÿһ�εĽ��
	 */
	private int dProgress;
	public MySeekbar(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		setOnSeekBarChangeListener(this);
		getViewTreeObserver().addOnPreDrawListener(this);
		setMax(max);	
	}

	public void setSection(int select) {
		this.select = select;
		invalidate();
	}
	@Override
	public boolean onPreDraw() {
		// TODO Auto-generated method stub
		if (seekBarWidth == 0) {
			seekBarWidth = getWidth();
			dSize = seekBarWidth / select;
			dProgress=max/select;
			this.setThumb(getThumbDrawable(getContext(), R.drawable.dianji, dSize+8));
			setProgress(dProgress-dProgress/2);
		}
		return true;
	}

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {
		// TODO Auto-generated method stub
		// TODO Auto-generated method stub
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		Log.e("print", "onStart");
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		int progress=seekBar.getProgress();
		int location= progress/dProgress;
		if(location==select){
			location=location-1;
		}
		setProgress(dProgress*location+dProgress/2);
		Log.e("print", "location:"+location);
	}

	public Drawable getThumbDrawable(Context context, int drawableId, int width) {
		Bitmap bmp_9path = BitmapFactory.decodeResource(getResources(),
				drawableId);
		Bitmap bitmap = Bitmap.createBitmap(width, bmp_9path.getHeight(),
				Bitmap.Config.ARGB_8888);
		NinePatch np = new NinePatch(bmp_9path, bmp_9path.getNinePatchChunk(),
				null);
		RectF rectf_9path = new RectF(0, 0, width, bmp_9path.getHeight());
		Canvas canvas = new Canvas(bitmap);
		np.draw(canvas, rectf_9path);
		return new BitmapDrawable(context.getResources(), bitmap);
	}

}
